package controller

import (
	"appengine"
	"entity"
	"fmt"
	"funcMap"
	"html/template"
	"model"
	"net/http"
	"search"
	"strconv"
	"strings"
)

func Search(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	c.Infof("Calling search.go")
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	strQuery := r.URL.Path
	strQuery = strings.Replace(strQuery, "/search/", "", -1)

	if len(strings.TrimSpace(strQuery)) > 0 {

		//Get setting
		var setting entity.Setting
		if err := model.GetCurrentSetting(c, &setting); err != nil {
			fmt.Fprintln(w, "Look like you just start this application, please come admin page to setting your page !")
			return
		}

		//Get template
		var currentTemplate entity.Template
		if err := model.GetTemplate(c, setting.CurrentTemplateID, &currentTemplate); err != nil {
			fmt.Fprintln(w, "Look like you just start this application, no template avaiable ! Please come admin page to setting your page !")
			return
		}

		//Page handle
		pagePara := r.FormValue("page")
		var page int
		if i, err := strconv.Atoi(pagePara); err != nil {
			page = 1
		} else {
			if i > 0 {
				page = i
			}
		}

		listNews, err := search.SearchNews(c, strQuery, page)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		//Get recent view
		recent, err := model.ListRecentNews(c)
		if err != nil {
			c.Errorf("Error when get Recent View at Homepage !")
		}

		//Get list category
		listCategory, err := model.ListCategory(c)
		if err != nil {
			c.Errorf("Error when get List Category at Homepage !")
		}

		//Get tag pool
		tagPool, err := model.TagPool(c)
		if err != nil {
			c.Errorf("Error when get Tag Pool at Homepage !")
		}

		//Check if have next page
		var hasNextPage bool = false
		var hasPreviousPage bool = false
		var nextPage int = 0
		var previousPage int = 0
		if len(listNews) > model.NewsLimit {
			hasNextPage = true
			nextPage = page + 1
			listNews = listNews[0 : len(listNews)-1]
		}
		if page > 1 {
			hasPreviousPage = true
			previousPage = page - 1
		}

		// Map function to use
		funcMap := template.FuncMap{
			"GetYear":      funcMap.GetYear,
			"GetMonth":     funcMap.GetMonth,
			"GetMonthName": funcMap.GetMonthName,
			"GetDay":       funcMap.GetDay,
			"GetCategory":  funcMap.GetCategoryNewsSearch,
		}

		//Add data to template
		data := map[string]interface{}{
			"strQuery":        strQuery,
			"listNews":        listNews,
			"page":            page,
			"hasNextPage":     hasNextPage,
			"nextPage":        nextPage,
			"hasPreviousPage": hasPreviousPage,
			"previousPage":    previousPage,
			"listCategory":    listCategory,
			"tagPool":         tagPool,
			"recent":          recent,
			"setting":         setting,
			"domainName":      r.Host,
		}

		t := template.Must(template.New("Category").Funcs(funcMap).Parse(currentTemplate.Search))
		if err := t.Execute(w, data); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	} else {
		fmt.Fprintln(w, "Invalid query string !")
	}

}
